package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zbkj.common.constants.MerchantConstants;
import com.zbkj.common.constants.ProductConstants;
import com.zbkj.common.enums.BrandEnumNew;
import com.zbkj.common.enums.RoleEnum;
import com.zbkj.common.exception.AppException;
import com.zbkj.common.model.admin.SystemAdmin;
import com.zbkj.common.model.brand.Brand;
import com.zbkj.common.model.city.CityRegionEntity;
import com.zbkj.common.model.page.PageDiy;
import com.zbkj.common.model.product.ProductCategory;
import com.zbkj.common.model.product.ProductCategoryBrand;
import com.zbkj.common.model.product.ProductLibrary;
import com.zbkj.common.model.system.SystemConfig;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.BrandNameSearchRequest;
import com.zbkj.common.request.BrandSearchRequest;
import com.zbkj.common.request.PageParamRequest;
import com.zbkj.common.request.ProductLibrarySearchRequest;
import com.zbkj.common.request.brand.*;
import com.zbkj.common.response.*;
import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.result.MerchantResultCode;
import com.zbkj.common.utils.*;
import com.zbkj.common.vo.BrandInfoVo;
import com.zbkj.common.vo.DateLimitUtilVo;
import com.zbkj.common.vo.LoginUserVo;
import com.zbkj.service.dao.BrandDao;
import com.zbkj.service.service.*;
import com.zbkj.service.util.BrandUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author RW
 * @date 2024/10/16 15:32
 */
@Slf4j
@Service
public class BrandServiceImpl extends ServiceImpl<BrandDao, Brand> implements BrandService {

  @Autowired
  private BrandDao dao;
  @Autowired
  private SystemAdminService  adminService;
    @Autowired
    private TransactionTemplate transactionTemplate;
    @Autowired
    private SystemNotificationService systemNotificationService;
    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private SystemAttachmentService systemAttachmentService;
    @Autowired
    private CityRegionService regionService;

    @Autowired
    private ProductService productService;

    @Autowired
    private SystemConfigService configService;

    @Autowired
    private ProductCategoryService  categoryService;

    @Autowired
    private ProductCategoryBrandService productCategoryBrandService;

    @Autowired
    private PageDiyService pageDiyService;

    @Autowired
    private ProductLibraryService productLibraryService;

    @Autowired
    private SystemGroupService systemGroupService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SystemAdminService systemAdminService;

    @Autowired
    private SystemRoleService systemRoleService;

    String BRAND_INFO_LOGIN = "brand:info:login";

  @Override
  public PageInfo<BrandPageResponse> getAdminPage(BrandRequest searchRequest, PageParamRequest pageParamRequest) {
      Page<Brand> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
      LambdaQueryWrapper<Brand> lqw = getAdminPageWrapperBySearch(searchRequest);
//      String sql = lqw.getSqlSegment();
//      log.info("sql{}", sql);
      List<Brand> merchantList = dao.selectList(lqw);
      if (CollUtil.isEmpty(merchantList)) {
       return CommonPage.copyPageInfo(page, CollUtil.newArrayList());
      }
      List<BrandPageResponse> responseList = merchantList.stream().map(e -> {
          BrandPageResponse response = new BrandPageResponse();
       BeanUtils.copyProperties(e, response);
       return response;
      }).collect(Collectors.toList());
      return CommonPage.copyPageInfo(page, responseList);
  }
    private LambdaQueryWrapper<Brand> getAdminPageWrapperBySearch(BrandRequest searchRequest) {
        LambdaQueryWrapper<Brand> lqw = Wrappers.lambdaQuery();
        if (ObjectUtil.isNotNull(searchRequest.getName())) {
            lqw.like(Brand::getName, searchRequest.getName());
        }
        if (ObjectUtil.isNotNull(searchRequest.getPhone())) {
            lqw.eq(Brand::getPhone, searchRequest.getPhone());
        }
        if (ObjectUtil.isNotNull(searchRequest.getRealName())) {
            lqw.eq(Brand::getRealName, searchRequest.getRealName());
        }
        if (ObjectUtil.isNotNull(searchRequest.getIsSelf())) {
            lqw.eq(Brand::getIsSelf, searchRequest.getIsSelf());
        }
        if (ObjectUtil.isNotNull(searchRequest.getIsSwitch())) {
            lqw.eq(Brand::getIsSwitch, searchRequest.getIsSwitch());
        }
  /*      if (StrUtil.isNotBlank(searchRequest.getKeywords())) {
            String keywords = URLUtil.decode(searchRequest.getKeywords());
            lqw.and(i -> i.like(Brand::getName, keywords)
//                    .or().apply(StrUtil.format(" find_in_set('{}', keywords)", keywords)));
                    .or().apply(" find_in_set({0}, keywords)", keywords));
        }*/
        if (StrUtil.isNotBlank(searchRequest.getKeywords())) {
            String keywords = URLUtil.decode(searchRequest.getKeywords());
            lqw.and(i -> i.like(Brand::getName, keywords)
                    .or().apply(" find_in_set({0}, keywords)", keywords));
        }

        if (StrUtil.isNotBlank(searchRequest.getDateLimit())) {
            DateLimitUtilVo dateLimitUtilVo = CrmebDateUtil.getDateLimit(searchRequest.getDateLimit());
            lqw.between(Brand::getCreateTime, dateLimitUtilVo.getStartTime(), dateLimitUtilVo.getEndTime());
        }
        lqw.eq(Brand::getIsDel, false);
        return lqw;
    }

    @Override
    public boolean add(BrandAddRequest request) {
        // 检查商户名or商户账号or商户手机号是否重复
//         || merchantApplyService.checkMerchantName(request.getName()) 申请提交
        if (checkMerchantName(request.getName())) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "商户名已存在");
        }
//         || merchantApplyService.checkMerchantPhone(request.getPhone()) 申请提交
        if (checkMerchantPhone(request.getPhone())) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "商户手机号已存在");
        }
        if (adminService.checkAccount(request.getPhone())) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "商户手机号已存在");
        }
        LoginUserVo loginUserVo = SecurityUtil.getLoginUserVo();

        Boolean execute = transactionTemplate.execute(e -> {
            Brand brand = new Brand();
            BeanUtils.copyProperties(request, brand);
            if (StrUtil.isNotBlank(brand.getPicUrl())) {
                brand.setPicUrl(systemAttachmentService.clearPrefix(brand.getPicUrl()));
            }
            brand.setCreateType(MerchantConstants.CREATE_TYPE_ADMIN);
            brand.setCreateId(loginUserVo.getUser().getId());
            brand.setCreateTime(DateUtil.date());
            brand.setShareUrl(brand.getShareUrl());
          /*  LambdaQueryWrapper<CityRegionEntity> wq = new LambdaQueryWrapper<CityRegionEntity>();
            wq.eq(CityRegionEntity::getProvinceName, request.getProvinceName());
            if (Objects.equals(request.getCityName(), "市辖区")){
                wq.eq(CityRegionEntity::getCityName, request.getProvinceName());
            }else {
                wq.eq(CityRegionEntity::getCityName, request.getCityName());
            }
            wq.eq(CityRegionEntity::getDistrictName, request.getDistrictName());
            wq.eq(CityRegionEntity::getTownName, request.getTownName());
            CityRegionEntity one = regionService.getOne(wq);
            if (Objects.equals(request.getCityName(), "市辖区")){
                brand.setAddressDetail(one.getProvinceName()+"-"+one.getProvinceName()+"-"+one.getDistrictName()+"-"+one.getTownName());
            }else{
                brand.setAddressDetail(one.getProvinceName()+"-"+one.getCityName()+"-"+one.getDistrictName()+"-"+one.getTownName());
            }
            brand.setProvinceName(one.getProvinceName());
            brand.setCityName(one.getCityName());
            brand.setDistrictName(one.getDistrictName());
            brand.setTownName(one.getTownName());
            brand.setProvinceId(one.getProvinceId());
            brand.setCityId(one.getCityId());
            brand.setDistrictId(one.getDistrictId());
            brand.setTownId(one.getTownId());
*/
            boolean aBoolean = save(brand);
            SystemAdmin merchantAdmin = initMerchantAdmin(request.getPhone(), request.getName());
            merchantAdmin.setBrandId(brand.getId());
            adminService.save(merchantAdmin);
            brand.setCreateId(merchantAdmin.getId());
            dao.updateById(brand);
            initBrandConfig(merchantAdmin.getId());
            ProductCategoryBrand categoryBrand = new ProductCategoryBrand();
            List<ProductCategory> list = categoryService.list();
            for (ProductCategory productBrandCategory : list) {
                categoryBrand.setBrandId(merchantAdmin.getId());
                categoryBrand.setIcon(productBrandCategory.getIcon());
                categoryBrand.setLevel(productBrandCategory.getLevel());
                categoryBrand.setName(productBrandCategory.getName());
                categoryBrand.setPid(productBrandCategory.getPid());
                categoryBrand.setSort(productBrandCategory.getSort());
                categoryBrand.setCategoryId(productBrandCategory.getId());
                categoryBrand.setIsDel(productBrandCategory.getIsDel());
                categoryBrand.setCreateTime(DateUtil.date());
                categoryBrand.setUpdateTime(DateUtil.date());
                categoryBrand.setIsShow(productBrandCategory.getIsShow());
                productCategoryBrandService.save(categoryBrand);
            }
            PageDiy pageDiy = pageDiyService.getFirst();
            PageDiy pageDiys = new PageDiy();
            pageDiys.setBrandId(merchantAdmin.getId());
            pageDiys.setValue(pageDiy.getValue());
            pageDiys.setName(brand.getName().replace("崇仁预见", ""));
            pageDiys.setTitle(brand.getName());
            pageDiys.setCoverImage(pageDiy.getCoverImage());
            pageDiys.setTemplateName(pageDiy.getTemplateName());
            pageDiys.setVersion(pageDiy.getVersion());
            pageDiys.setAddTime(DateUtil.date());
            pageDiys.setIsBgPic(pageDiy.getIsBgPic());
            pageDiys.setColorPicker(pageDiy.getColorPicker());
            pageDiys.setIsBgColor(pageDiy.getIsBgColor());
            pageDiys.setColorPicker(pageDiy.getColorPicker());
            pageDiys.setBgPic(pageDiy.getBgPic());
            pageDiys.setTitleColor(pageDiy.getTitleColor());
            pageDiys.setTitleBgColor(pageDiy.getTitleBgColor());
            pageDiys.setIsDefault(1);
            pageDiyService.save(pageDiys);

            // 复制一份组合数据（首页装修）
            try {
                if (systemGroupService.getNotExists(merchantAdmin.getId())) {
                    systemGroupService.copyDefault(merchantAdmin.getId());
                }
            } catch (Exception e1) {
                log.warn("复制默认的组合数据到当前品牌商失败");
            }

            // 代理
            systemRoleService.checkAndCreateAgentRole();

            // 底部菜单
            Integer brandId =merchantAdmin.getId();
            if (systemGroupService.getNotExists(brandId)) {
                systemGroupService.copyDefault(brandId);
            }
            // 修改配置信息
            List<String> ids = Arrays.asList("wechat_share_title", "seo_title", "site_name", "wechat_share_synopsis",
                    "wechat_share_title", "site_url", "mer_site_url", "api_url");
            List<SystemConfig> configList = systemConfigService.getListByBrandId(brand.getId(), ids);
            List<SystemConfig> updateList = new ArrayList<>();
            if (CollUtil.isNotEmpty(configList)) {
                configList.forEach(config -> {
                    if (config.getName().equals("wechat_share_title")) {
                        config.setValue(brand.getName());
                        updateList.add(config);
                    } else if (config.getName().equals("seo_title")) {
                        config.setValue(brand.getName());
                        updateList.add(config);

                    } else if (config.getName().equals("site_name")) {
                        config.setValue(brand.getName());
                        updateList.add(config);

                    } else if (config.getName().equals("wechat_share_synopsis")) {
                        config.setValue(brand.getName() + "欢迎您");
                        updateList.add(config);

                    } else if (config.getName().equals("wechat_share_title")) {
                        config.setValue(brand.getName());
                        updateList.add(config);

                    } else if (config.getName().equals("site_url")) {
                        config.setValue("https://" + brand.getShareUrl());
                        updateList.add(config);

                    } else if (config.getName().equals("mer_site_url")) {
                        if (brand.getShareUrl().contains("brand.xingtu")) {
                            String brandName = brand.getShareUrl().substring(0, brand.getShareUrl().indexOf("."));
                            String uri = brand.getShareUrl().substring(brand.getShareUrl().indexOf("."));
                            config.setValue("https://" + brandName + "-merchant" + uri);
                            updateList.add(config);

                        }
                    } else if (config.getName().equals("api_url") && config.getFormId().equals(31)) {
                        String brandName = brand.getShareUrl().substring(0, brand.getShareUrl().indexOf("."));
                        String uri = brand.getShareUrl().substring(brand.getShareUrl().indexOf("."));
                        config.setValue("https://" + brandName + "-admin" + uri);
                        updateList.add(config);

                    }
                });
                if (CollUtil.isNotEmpty(updateList)) {
                    systemConfigService.updateBatchById(updateList);
                }
            }

            // 检查品牌商的通知配置
            systemNotificationService.checkBrandConfig(brand.getId());

            if (!aBoolean) {
                log.error("后台新增品牌商事务失败！准备回滚");
                e.setRollbackOnly();
            }
            return Boolean.TRUE;
        });
        /*if (execute) {
            SystemNotification payNotification = systemNotificationService.getByMark(NotifyConstants.AUDIT_SUCCESS_MARK);
            // 发送短信
            if (StrUtil.isNotBlank(request.getPhone()) && payNotification.getIsSms().equals(1)) {
                String merSiteUrl = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_KEY_MERCHANT_SITE_URL);
                if (StrUtil.isBlank(merSiteUrl)) {
                    merSiteUrl = "";
                }
                try {
                    smsService.sendMerchantAuditSuccessNotice(request.getPhone(), DateUtil.date().toString(),
                            request.getName(), request.getPhone(),
                            "000000",
                            merSiteUrl);
                } catch (Exception e) {
                    log.error("品牌商创建成功短信发送异常，{}", e.getMessage());
                }
            }
        }*/
        return execute;
    }
    // 初始化品牌配置
    private boolean initBrandConfig(Integer id) {
        try {
            // 使用 configService 进行配置初始化 默认获取平台
            List<SystemConfig> list = configService.list(new LambdaQueryWrapper<SystemConfig>().eq(SystemConfig::getTypeForm, 0));
            for (SystemConfig systemConfig : list) {
                systemConfig.setTypeForm(id);
                configService.save(systemConfig);
            }
            return true;
        } catch (Exception ex) {
            log.error("初始化品牌配置失败", ex);
            return false;
        }

    }

    @Override
    public boolean edit(BrandUpdateRequest request) {
        Brand brand = getByIdException(request.getId());
        if (!request.getName().equals(brand.getName())) {
            if (checkMerchantName(request.getName(), request.getId())) {
                throw new AppException(CommonResultCode.VALIDATE_FAILED, "商户名称已存在");
            }
        }
        Brand tempMerchant = new Brand();
        BeanUtils.copyProperties(request, tempMerchant);
        tempMerchant.setShareUrl(tempMerchant.getShareUrl());
        LambdaQueryWrapper<CityRegionEntity> wq = new LambdaQueryWrapper<CityRegionEntity>();
        wq.eq(CityRegionEntity::getProvinceName, request.getProvinceName());
        if (Objects.equals(request.getCityName(), "市辖区")){
            wq.eq(CityRegionEntity::getCityName, request.getProvinceName());
        }else {
            wq.eq(CityRegionEntity::getCityName, request.getCityName());
        }
        wq.eq(CityRegionEntity::getDistrictName, request.getDistrictName());
        wq.eq(CityRegionEntity::getTownName, request.getTownName());
        CityRegionEntity one = regionService.getOne(wq);
        if (ObjectUtil.isNotNull(one)) {
            if (Objects.equals(request.getCityName(), "市辖区")) {
                tempMerchant.setAddressDetail(one.getProvinceName() + "-" + one.getProvinceName() + "-" + one.getDistrictName() + "-" + one.getTownName());
            } else {
                tempMerchant.setAddressDetail(one.getProvinceName() + "-" + one.getCityName() + "-" + one.getDistrictName() + "-" + one.getTownName());
            }
            tempMerchant.setProvinceName(one.getProvinceName());
            tempMerchant.setCityName(one.getCityName());
            tempMerchant.setDistrictName(one.getDistrictName());
            tempMerchant.setTownName(one.getTownName());
            tempMerchant.setProvinceId(one.getProvinceId());
            tempMerchant.setCityId(one.getCityId());
            tempMerchant.setDistrictId(one.getDistrictId());
            tempMerchant.setTownId(one.getTownId());
        }
        if (StrUtil.isNotBlank(tempMerchant.getPicUrl())) {
            tempMerchant.setPicUrl(systemAttachmentService.clearPrefix(tempMerchant.getPicUrl()));
        }
        return dao.updateById(tempMerchant) > 0;
    }

    @Override
    public Brand getByIdException(Integer id) {
        Brand brand = getById(id);
        if (ObjectUtil.isNull(brand) || brand.getIsDel()) {
            throw new AppException("品牌商不存在");
        }
        return brand;
    }

    @Override
    public boolean updatePhone(BrandUpdatePhoneRequest request) {
        Brand brand = getByIdException(request.getId());
        if (request.getPhone().equals(brand.getPhone())) {
            return Boolean.TRUE;
        }
//        || merchantApplyService.checkMerchantPhone(request.getPhone())
        if (checkMerchantPhone(request.getPhone(), request.getId()) ) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "手机号已存在");
        }
        if (adminService.checkAccount(request.getPhone())) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "手机号已存在");
        }
        brand.setPhone(request.getPhone());
        SystemAdmin systemAdmin = adminService.getDetail(brand.getCreateId());
        String pwd = "";
        try {
            pwd = CrmebUtil.decryptPassowrd(systemAdmin.getPwd(), systemAdmin.getAccount());
        } catch (Exception e) {
            e.printStackTrace();
        }
        systemAdmin.setAccount(request.getPhone());
        systemAdmin.setPhone(request.getPhone());
        systemAdmin.setPwd(CrmebUtil.encryptPassword(pwd, request.getPhone()));
        return Boolean.TRUE.equals(transactionTemplate.execute(e -> {
            updateById(brand);
            adminService.updateById(systemAdmin);
            return Boolean.TRUE;
        }));
    }

    @Override
    public boolean resetPassword(Integer id) {
        Brand brand = getByIdException(id);
        SystemAdmin systemAdmin = adminService.getDetail(brand.getCreateId());
        systemAdmin.setPwd(CrmebUtil.merchantInitPassword(systemAdmin.getAccount()));
        return adminService.updateById(systemAdmin);
    }

    @Override
    public BrandDetailResponse getPlatformDetail(Integer id) {
        Brand brand = getByIdException(id);
        BrandDetailResponse response = new BrandDetailResponse();
        BeanUtils.copyProperties(brand, response);
        response.setPhone(brand.getPhone());
        return response;
    }

    @Override
    public boolean close(Integer id) {
        Brand brand = getByIdException(id);
        if (!brand.getIsSwitch()) {
            throw new AppException(MerchantResultCode.MERCHANT_SWITCH_CLOSE);
        }
        // 1.修改商户状态，2.强制下架商户所有商品,3.手动关闭的商户，商品审核状态自动切换为需要审核状态
        brand.setIsSwitch(false);
        brand.setProductSwitch(true);
        return transactionTemplate.execute(e -> {
            dao.updateById(brand);
            productService.forcedRemovalAll(brand.getId());
            return Boolean.TRUE;
        });
    }

    @Override
    public boolean open(Integer id) {
        Brand brand = getByIdException(id);
        if (brand.getIsSwitch()) {
            throw new AppException(MerchantResultCode.MERCHANT_SWITCH_OPEN);
        }
//        openMerchantValidator(brand);
        brand.setIsSwitch(true);
        return dao.updateById(brand) > 0;
    }

    @Override
    public BrandHeaderNumResponse getListHeaderNum(BrandRequest searchRequest) {
        Integer openNum = getOpenNum(searchRequest);
        // 关闭的商户数
        Integer closeNum = getCloseNum(searchRequest);
        return new BrandHeaderNumResponse(openNum, closeNum);
    }

    @Override
    public PageInfo<BrandLinkResponse> brandLink(BrandLink brandLink, PageParamRequest pageParamRequest) {
        Page<Brand> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        LambdaQueryWrapper<Brand> lqw =new LambdaQueryWrapper<>();
        lqw.eq(Brand::getIsSelf, 1);
        lqw.eq(Brand::getIsSwitch, 1);
        lqw.like(StrUtil.isNotBlank(brandLink.getShareUrl()), Brand::getShareUrl, brandLink.getShareUrl());
        List<Brand> merchantList = dao.selectList(lqw);
        if (CollUtil.isEmpty(merchantList)) {
            return CommonPage.copyPageInfo(page, CollUtil.newArrayList());
        }
        List<BrandLinkResponse> responseList = merchantList.stream().map(e -> {
            BrandLinkResponse response = new BrandLinkResponse();
            BeanUtils.copyProperties(e, response);
            return response;
        }).collect(Collectors.toList());
        return CommonPage.copyPageInfo(page, responseList);
    }

    @Override
    public PageInfo<BrandResponse> getAdminListBrand(BrandSearchRequest request, PageParamRequest pageParamRequest) {
        Page<Brand> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        LambdaQueryWrapper<Brand> lqw = Wrappers.lambdaQuery();
        lqw.select(Brand::getId, Brand::getName, Brand::getRealName, Brand::getShareUrl, Brand::getPhone);
        if (StrUtil.isNotBlank(request.getName())) {
            lqw.eq(Brand::getName, request.getName());
        }
        lqw.eq(Brand::getIsDel, false);
        lqw.eq(Brand::getIsSwitch, true);
        lqw.orderByAsc(Brand::getId);
        List<Brand> articleList = dao.selectList(lqw);

        List<BrandResponse> responseList = new ArrayList<>();
        if (CollUtil.isEmpty(articleList)) {
            return CommonPage.copyPageInfo(page, responseList);
        }
        for (Brand brand : articleList) {
            BrandResponse response = new BrandResponse();
            BeanUtils.copyProperties(brand, response);
            responseList.add(response);
        }
        return CommonPage.copyPageInfo(page, responseList);
    }

    @Override
    public PageInfo<BrandResponse> getSelectedBrandListBrand(BrandSearchRequest searchRequest, PageParamRequest pageParamRequest) {
        ProductLibrarySearchRequest request = new ProductLibrarySearchRequest();
        request.setType(ProductConstants.PRODUCT_LIBRARY_TYPE_BRAND);
        List<ProductLibrary> productLibraryList = productLibraryService.getAdminListBrand(request);
        List<Integer> productLibraryIdList = productLibraryList.stream().map(ProductLibrary::getLinkId).collect(Collectors.toList());
        PageInfo<BrandResponse> adminListBrand = getAdminListBrand(searchRequest, pageParamRequest);
        adminListBrand.getList().stream().forEach(e -> {
            e.setIsSelected(productLibraryIdList.contains(e.getId()));
        });
        return adminListBrand;
    }

    @Override
    public List<Integer> getEnableBrandList() {
        LambdaQueryWrapper<Brand> lqw = Wrappers.lambdaQuery();
        lqw.eq(Brand::getIsSwitch, 1);
        return dao.selectList(lqw).stream().map(Brand::getId).distinct().collect(Collectors.toList());
    }

    /**
     * 根据推广链接获取品牌商名称
     * @param request 请求参数
     * @return
     */
    @Override
    public BrandNameResponse getName(BrandNameSearchRequest request) {
        LambdaQueryWrapper<Brand> lqw = Wrappers.lambdaQuery();
        lqw.select(Brand::getName);
        lqw.eq(Brand::getIsDel, false);
        lqw.eq(Brand::getShareUrl, CommonUtil.extractDomain(request.getShareUrl()));
        Brand brand = getOne(lqw);
        if (ObjectUtil.isNotNull(brand)) {
            BrandNameResponse response = new BrandNameResponse();
            response.setName(brand.getName());
            return response;
        }
        return null;
    }

    @Override
    public boolean updatePhonePlarform(BrandUpdatePhoneRequest request) {
        Brand brand = getByIdException(request.getId());
        if (request.getPhone().equals(brand.getPhone())) {
            return Boolean.TRUE;
        }
        // 检查其他品牌商是否有相同手机号
        if (checkMerchantPhone(request.getPhone(), request.getId()) ) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "手机号已存在");
        }
        // 检查当前品牌商下的管理员是否有这个手机号
        if (adminService.checkAccountPlarform(request.getPhone(), brand.getId())) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "手机号已存在");
        }
        brand.setPhone(request.getPhone());
        SystemAdmin systemAdmin = adminService.getDetail(brand.getCreateId());
        String pwd = "";
        try {
            pwd = CrmebUtil.decryptPassowrd(systemAdmin.getPwd(), systemAdmin.getAccount());
        } catch (Exception e) {
            e.printStackTrace();
        }
        systemAdmin.setAccount(request.getPhone());
        systemAdmin.setPhone(request.getPhone());
        systemAdmin.setPwd(CrmebUtil.encryptPassword(pwd, request.getPhone()));
        return Boolean.TRUE.equals(transactionTemplate.execute(e -> {
            updateById(brand);
            adminService.updateById(systemAdmin);
            return Boolean.TRUE;
        }));
    }

    @Override
    public List<Brand> getAllEnableBrandList() {
        LambdaQueryWrapper<Brand> lqw = Wrappers.lambdaQuery();
        lqw.select(Brand::getId, Brand::getName, Brand::getShareUrl, Brand::getCreateId);
        lqw.eq(Brand::getIsSwitch, 1);
        lqw.eq(Brand::getIsDel, 0);
        lqw.orderByAsc(Brand::getCreateTime);
        return list(lqw);
    }

    /**
     * 刷新品牌商缓存
     */
    @Override
    public void cacheBrandInfo() {
        List<Brand> brandList = this.getAllEnableBrandList();
        List<BrandInfoVo> brandInfoVoList = new ArrayList<>();
        for (Brand brand : brandList) {
            BrandInfoVo brandInfoVo = new BrandInfoVo();
            BeanUtils.copyProperties(brand, brandInfoVo);
            //localhost用于测试
            if (brandInfoVo.getShareUrl().contains("localhost")){
                brandInfoVo.setShareUrl("localhost");
            }else{
                // 去掉后缀(zmgj.brand)
                int i = brandInfoVo.getShareUrl().indexOf(".");
                String substring = brandInfoVo.getShareUrl().substring(0, i);
                brandInfoVo.setShareUrl(substring);
            }

            // 登陆人id
            SystemAdmin admin = systemAdminService.getOne(new LambdaQueryWrapper<SystemAdmin>()
                    .select(SystemAdmin::getId).eq(SystemAdmin::getBrandId, brandInfoVo.getId()));
            if (admin != null) {
                brandInfoVo.setSysAdminId(admin.getId());
            } else {
                brandInfoVo.setSysAdminId(-1);
            }
            brandInfoVoList.add(brandInfoVo);
        }
        String json = new Gson().toJson(brandInfoVoList);
        log.info("刷新品牌商缓存json = " + json);
        redisUtil.set(BRAND_INFO_LOGIN, json);
    }

    @Override
    public Integer getBrandId(String url) {
        Object brandInfo = redisUtil.get(BRAND_INFO_LOGIN);
        if (brandInfo == null) {
            throw new AppException("系统服务异常");
        }
        List<BrandInfoVo> brandInfoVoList = new Gson().fromJson(brandInfo.toString(), new TypeToken<List<BrandInfoVo>>() {
        }.getType());
        for (BrandInfoVo brandInfoVo : brandInfoVoList) {
            log.info("brandInfoVo.getShareUrl() = " + brandInfoVo.getShareUrl());
            /*if (url.contains(brandInfoVo.getShareUrl() + ".brand")
                    || url.contains(brandInfoVo.getShareUrl() + "-merchant.brand")
                    || url.contains(brandInfoVo.getShareUrl() + "-admin.brand")) {
                    log.info("识别品牌商:{}/{}/{}/【{}】", brandInfoVo.getId(), brandInfoVo.getCreateId(), brandInfoVo.getShareUrl(), url);
                return brandInfoVo.getSysAdminId();
            }*/
            if (url.contains(brandInfoVo.getShareUrl() + ".brand")
                    || url.contains(brandInfoVo.getShareUrl() + "-merchant.brand")
                    || url.contains(brandInfoVo.getShareUrl() + "-admin.brand")
                    //用于本地开发测试
                    || url.contains(brandInfoVo.getShareUrl() + ".168")
                    || url.contains(brandInfoVo.getShareUrl()+":")) {
                log.info("识别品牌商:{}/{}/{}/【{}】", brandInfoVo.getId(), brandInfoVo.getCreateId(), brandInfoVo.getShareUrl(), url);
                return brandInfoVo.getSysAdminId();
            }
        }
        // 固定模式
        Integer id = BrandEnumNew.getId(url);
        if (id > 0) {
            SystemAdmin admin = systemAdminService.getOne(new LambdaQueryWrapper<SystemAdmin>()
                    .select(SystemAdmin::getId).eq(SystemAdmin::getBrandId, id));
            if (admin != null) {
                return admin.getId();
            }
        }
        return id;
    }

    @Override
    public String getNameById(Integer brandId) {
        LambdaQueryWrapper<Brand> lqw = Wrappers.lambdaQuery();
        lqw.select(Brand::getName);
        lqw.eq(Brand::getIsDel, false);
        lqw.eq(Brand::getId, brandId);
        Brand brand = getOne(lqw);
        if (ObjectUtil.isNotNull(brand)) {
            return brand.getName();
        }
        return null;
    }

    @Override
    public List<Integer> getIdsByName(String name) {
        LambdaQueryWrapper<Brand> lqw = Wrappers.lambdaQuery();
        lqw.select(Brand::getId);
        lqw.eq(Brand::getIsDel, false);
        lqw.like(Brand::getName, name);
        List<Brand> list = list(lqw);
        if (CollUtil.isNotEmpty(list)) {
            return list.stream().map(Brand::getId).distinct().collect(Collectors.toList());
        }
        return null;
    }

    private Integer getOpenNum(BrandRequest searchRequest) {
        LambdaQueryWrapper<Brand> lqw = getAdminPageWrapperBySearch(searchRequest);
        lqw.eq(Brand::getIsSwitch, 1);
        return dao.selectCount(lqw);
    }

    private Integer getCloseNum(BrandRequest searchRequest) {
        LambdaQueryWrapper<Brand> lqw = getAdminPageWrapperBySearch(searchRequest);
        lqw.eq(Brand::getIsSwitch, 0);
        return dao.selectCount(lqw);
    }

    /**
     * 检查商户名是否重复
     *
     * @param name 商户名称
     */
    private Boolean checkMerchantName(String name) {
        LambdaQueryWrapper<Brand> lqw = Wrappers.lambdaQuery();
        lqw.select(Brand::getId);
        lqw.eq(Brand::getName, name);
        lqw.eq(Brand::getIsDel, false);
        lqw.last(" limit 1");
        Brand merchant = dao.selectOne(lqw);
        return ObjectUtil.isNotNull(merchant);
    }

    /**
     * 检查商户名是否重复
     *
     * @param name 商户名称
     * @param id   商户ID
     */
    private Boolean checkMerchantName(String name, Integer id) {
        LambdaQueryWrapper<Brand> lqw = Wrappers.lambdaQuery();
        lqw.select(Brand::getId);
        lqw.eq(Brand::getName, name);
        lqw.ne(Brand::getId, id);
        lqw.eq(Brand::getIsDel, false);
        lqw.last(" limit 1");
        Brand merchant = dao.selectOne(lqw);
        return ObjectUtil.isNotNull(merchant);
    }
    /**
     * 检查商户手机号是否重复
     *
     * @param phone 商户手机号
     * @return Boolean
     */
    private Boolean checkMerchantPhone(String phone) {
        LambdaQueryWrapper<Brand> lqw = Wrappers.lambdaQuery();
        lqw.select(Brand::getId);
        lqw.eq(Brand::getPhone, phone);
        lqw.eq(Brand::getIsDel, false);
        lqw.last(" limit 1");
        Brand merchant = dao.selectOne(lqw);
        return ObjectUtil.isNotNull(merchant);
    }
    /**
     * 检查商户手机号是否重复
     *
     * @param phone 商户手机号
     * @param id    商户ID
     * @return Boolean
     */
    private Boolean checkMerchantPhone(String phone, Integer id) {
        LambdaQueryWrapper<Brand> lqw = Wrappers.lambdaQuery();
        lqw.select(Brand::getId);
        lqw.eq(Brand::getPhone, phone);
        lqw.ne(Brand::getId, id);
        lqw.eq(Brand::getIsDel, false);
        lqw.last(" limit 1");
        Brand merchant = dao.selectOne(lqw);
        return ObjectUtil.isNotNull(merchant);
    }

    /**
     * 初始化品牌商账号
     *
     * @param account 账号
     * @param name    名称
     * @return SystemAdmin
     */
    private SystemAdmin initMerchantAdmin(String account, String name) {
        SystemAdmin systemAdmin = new SystemAdmin();
        systemAdmin.setAccount(account);
        systemAdmin.setPwd(CrmebUtil.merchantInitPassword(account));
        systemAdmin.setRealName(name);
        systemAdmin.setStatus(true);
        systemAdmin.setRoles(RoleEnum.BRAND_SUPER_ADMIN.getValue().toString());
        systemAdmin.setType(RoleEnum.BRAND_SUPER_ADMIN.getValue());
        systemAdmin.setPhone(account);
        return systemAdmin;
    }


 }
